<?php
/**
 * 商家入驻申请控制器
 * @version 0.1
 * @author ezhu <ezhu@jipukeji.com>
 */

namespace Home\Controller;

class SettleController extends HomeController{
    
    
    protected function _initialize(){
        parent::_initialize();
        parent::login();
        // 验证用户是否已注册 店铺
        $isSeller = D('Store')->isSeller(UID);
        if($isSeller){
            $this->redirect('Shop/Seller/login');
        }
    }
    
    /**
     * 商家入驻-协议
     */
    public function index(){
        // TODO：读取商家入驻协议，请阅读并同意入驻协议
        $data = M('Doc')->where(array('code'=>'open_store'))->find();
        $protocol = htmlspecialchars_decode($data['content']);
        $this->assign('protocol',$protocol);
        $this->meta_title = '入驻协议';
        $this->display();
    }
    
    
    /**
     * 商家入驻-开户行信息
     */
    public function step1(){
        if(IS_POST) {
            $param = array();
            $province = I('province');
            $city = I('city');
            $district = I('district');
            
            $param['bank_address'] = $this->validArea($province,$city,$district);
            $param['bank_account_name'] = I('bank_account_name');
            $param['bank_account_number'] = I('bank_account_number');
            $param['bank_name'] = I('bank_name');
            $param['bank_code'] = I('bank_code');
            $param['bank_licence_electronic'] = I('bank_licence_electronic');
            // 计算账号和开户行合并
            if(isset($_POST['is_settlement_account']) && !empty($_POST['is_settlement_account'])) {
                $param['is_settlement_account'] = 1;
                $param['settlement_bank_account_name'] = I('bank_account_name');
                $param['settlement_bank_account_number'] = I('bank_account_number');
                $param['settlement_bank_name'] = I('bank_name');
                $param['settlement_bank_code'] = I('bank_code');
                $param['settlement_bank_address'] = $param['bank_address'];
            } else {
                // 结算开户行所在地址
                $settle_province = I('settle_province');
                $settle_city = I('settle_city');
                $settle_district = I('settle_district');
                
                $param['is_settlement_account'] = 2;
                $param['settlement_bank_account_name'] = I('settlement_bank_account_name');
                $param['settlement_bank_account_number'] = I('settlement_bank_account_number');
                $param['settlement_bank_name'] = I('settlement_bank_name');
                $param['settlement_bank_code'] = I('settlement_bank_code');
                $param['settlement_bank_address'] = $this->validArea($settle_province,$settle_city,$settle_district);
            }
            $param['tax_registration_certificate'] = I('tax_registration_certificate');
            $param['taxpayer_id'] = I('taxpayer_id');
            $param['tax_registration_certificate_electronic'] = I('tax_registration_certificate_electronic');
            // 验证表单规则
            $rules = $this->step1_rules($param['is_settlement_account']);
            $model = D("StoreApply"); // 实例化模块
            if (!$model->validate($rules)->create()){
                // 如果创建失败 表示验证没有通过 输出错误提示信息
                $this->error($model->getError());
            }else{
                // 验证通过 可以进行其他数据操作
                $map['member_id'] = UID;
                $isExist = $model->where($map)->find();
                if(!empty($isExist)){
                    // 更新操作
                    $rst = $model->where($map)->save($param);
                }else{
                    $param['member_id'] = UID;
                    $param['ctime'] = time();
                    $rst = $model->add($param);
                }
                $rst !== false ? $this->success('添加成功！',U('step2')) : $this->error('操作失败！');
                exit;
            }
        }
        $this->meta_title = '开户行信息';
        $this->display();
    }
    
    
    /**
     * 表单内容验证
     * @param unknown $param
     */
    private function step1_rules($is_settlement_account=1) {
        if($is_settlement_account == 1){ // 合并
            $rules = array(
                    array('bank_account_name','require','银行开户名不能为空且必须小于50个字！'),
                    array('bank_account_number','require','银行账号不能为空且必须小于20个字！'),
                    array('bank_name','require','开户银行支行名称不能为空且必须小于50个字！'),
                    array('bank_code','require','支行联行号不能为空且必须小于20个字！'),
                    array('bank_address','require','开户行所在地不能为空！'),
                    array('bank_licence_electronic','require','请上传开户银行许可证电子版文件！'),
            
                    array('tax_registration_certificate','require','税务登记证号不能为空且必须小于20个字！'),
                    array('taxpayer_id','require','纳税人识别号！'),
                    array('tax_registration_certificate_electronic','require','请上传税务登记证号电子版文件！')
            );
        }else{
            $rules = array(
                    array('bank_account_name','require','银行开户名不能为空且必须小于50个字！'),
                    array('bank_account_number','require','银行账号不能为空且必须小于20个字！'),
                    array('bank_name','require','开户银行支行名称不能为空且必须小于50个字！'),
                    array('bank_code','require','支行联行号不能为空且必须小于20个字！'),
                    array('bank_address','require','开户行所在地不能为空！'),
                    array('bank_licence_electronic','require','请上传开户银行许可证电子版文件！'),
            
                    array('settlement_bank_account_name','require','银行开户名不能为空且必须小于50个字！'),
                    array('settlement_bank_account_number','require','银行账号不能为空且必须小于20个字！'),
                    array('settlement_bank_name','require','开户银行支行名称不能为空且必须小于50个字！'),
                    array('settlement_bank_code','require','支行联行号不能为空且必须小于20个字！'),
                    array('settlement_bank_address','require','开户行所在地不能为空！'),
            
                    array('tax_registration_certificate','require','税务登记证号不能为空且必须小于20个字！'),
                    array('taxpayer_id','require','纳税人识别号！'),
                    array('tax_registration_certificate_electronic','require','请上传税务登记证号电子版文件！')
            );
        }
        
        return $rules;
    }
    
    
    /**
     * 地区获取
     * @param number $province
     * @param number $city
     * @param number $district
     * @return boolean|string
     */
    public function validArea($province=0,$city=0,$district=0,$errMsg='请选择开户行所在地址'){
        if(empty($province) || empty($city) || empty($district)){
            $this->error($errMsg);
        }
        $str = '';
        $field = 'sub_name';
        $arr[] = $province;
        $arr[] = $city;
        $arr[] = $district;
        $map['id'] = array('in',$arr);
        $data = M('Area')->where($map)->order('`pid` ASC')->select();
        if(!empty($data)){
            foreach ($data as $key=>$val){
                if($val['deep'] != 3){
                    $str .= $val[$field].' ';
                }else{
                    $str .= $val['title'].' ';
                }
                
            }
        }
        return trim($str);
    }
    
    
    /**
     * 商家入驻-商家信息
     */
    public function step2(){
        // TODO:获取、验证商家信息并存入数据库
        if(IS_POST && IS_AJAX) {
            $param = array();
            // 店铺公司所在地
            $province = I('province');
            $city = I('city');
            $district = I('district');
            
            // 结算开户行所在地址
            $licence_province = I('licence_province');
            $licence_city = I('licence_city');
            $licence_district = I('licence_district');
            
            $param['member_name'] = get_username();
            $param['company_name'] = I('company_name');
            $param['company_address'] = $this->validArea($province,$city,$district,'请选择公司地址');
            $param['company_address_detail'] = I('company_address_detail');
            $param['company_phone'] = I('company_phone');
            $param['company_employee_count'] = I('company_employee_count');
            $param['company_registered_capital'] = I('company_registered_capital');
            $param['contacts_name'] = I('contacts_name');
            $param['contacts_phone'] = I('contacts_phone');
            $param['contacts_email'] = I('contacts_email');
            $param['business_licence_number'] = I('business_licence_number');
            $param['business_licence_address'] = $this->validArea($licence_province,$licence_city,$licence_district,'请选择营业执照所在地址');
            $param['business_licence_start'] = strtotime(I('business_licence_start'));
            $param['business_licence_end'] = strtotime(I('business_licence_end'));
            $param['business_sphere'] = I('business_sphere');
            $param['business_licence_number_electronic'] = I('business_licence_number_electronic');
            $param['organization_code'] = I('organization_code');
            $param['organization_code_electronic'] = I('organization_code_electronic');
            $param['general_taxpayer'] = I('general_taxpayer');

            $rules = $this->step2_rules();
        
            $model = D("StoreApply"); // 实例化模块
            if (!$model->validate($rules)->create()){
                // 如果创建失败 表示验证没有通过 输出错误提示信息
                $this->error($model->getError());
            }else{
                // 验证通过 可以进行其他数据操作
                $rst = false;
                $map['member_id'] = UID;
                // 更新操作
                $rst = $model->where($map)->save($param);
                $rst !== false ? $this->success('添加成功！',U('step3')) : $this->error('操作失败！');
                exit;
            }
        }
        $this->meta_title = '商家信息';
        $this->display();
    }
    
    
    /**
     * 公司信息验证规则
     * @return multitype:multitype:string
     */
    private function step2_rules(){
        $rules = array(
                array('company_name','1,50','公司名称不能为空且必须小于50个字！','1','length'),
                array('company_address_detail','1,50','公司详细地址不能为空且必须小于50个字！','1','length'),
                array('company_phone','is_mobile_number','公司电话不能为空！','1','function'),
                array('company_employee_count','1,6','公司人数不能为空且必须小于6个字！','1','length'),
                array('company_registered_capital','1,8','注册资金不能为空且必须小于8个字！','1','length'),
                array('contacts_name','1,20','联系人姓名不能为空且必须小于20个字！','1','length'),
                array('contacts_phone','is_mobile_number','联系人电话不能为空！','1','function'),
                array('contacts_email','email','请输入正确的电子邮箱！'),
                array('business_licence_number','1,20','营业执照号不能为空且必须小于20个字！','1','length'),
        
                array('business_licence_start','require','营业执照有效期不能为空！'),
                array('business_licence_end','require','营业执照有效期不能为空！'),
                array('business_sphere','1,50','法定经营范围不能为空且必须小于50个字！','1','length'),
                array('business_licence_number_electronic','require','请上传营业执照电子版！'),
                array('organization_code','1,20','组织机构代码不能为空且必须小于20个字！','1','length'),
                array('organization_code_electronic','require','请上传组织机构代码电子版！'),
        
                array('general_taxpayer','require','请上传纳税人证明电子版！'),
            );
        
        return $rules;
    }
    
    
    
    /**
     * 商家入驻-店铺信息设置
     */
    public function step3(){
        // TODO:获取、验证商家信息并存入数据库
        if(IS_POST && IS_AJAX){
            $data=I('post.');
            // 全选按钮选择
            if (isset($data['all_cate'])) {

                if ( !empty($data['store_class_ids']) && !empty($data['store_class_names'])) {
                    $store_class_ids = $data['store_class_ids'];
                    $store_class_names = $data['store_class_names'];
                }else{
                    $tree = D('ItemCategory')->getTree(0,'id,pid,name');
                    $idss = $names = array();
                    foreach ($tree as $key => $value) {
                        if ($value['_']) {
                            foreach ($value['_'] as $ke => $val) {
                                if (isset($val['_'])) {
                                    foreach ($val['_'] as $k => $v) {
                                        $_ids[$ke][$k][] = $value['id'].','.$val['id'].','.$v['id'];
                                        $_name[$ke][$k][] = $value['name'].','.$val['name'].','.$v['name'];
                                    }
                                }else{
                                    $_idss[$ke][] = $value['id'].','.$val['id'];
                                    $_names[$ke][] = $value['name'].','.$val['name'];
                                }
                            }
                        }else{
                            $ids[$key] = $value['id'];
                            $name[$key] = $value['name'];
                        }
                        $idss[] = $ids;
                        $names[] = $name;
                    }
                    
                    $temp = $tep = $data = array();
                    foreach ($names as $key => $value) {
                        $temp = array_merge($temp,$value);
                    }
                    foreach ($idss as $key => $value) {
                        $tep = array_merge($tep,$value);
                    }
                    $store_class_names = array_unique($temp);
                    $store_class_ids = array_unique($tep);
                    
                    foreach ($_names as $key => $value) {
                       foreach ($value as $k => $v) {
                           $store_class_names[] = $v;
                       }
                    }
                    foreach ($_idss as $key => $value) {
                        foreach ($value as $k => $v) {
                            $store_class_ids[] = $v;
                        }
                    }
                    foreach ($_name as $key => $value) {
                       foreach ($value as $k => $v) {
                           foreach ($v as $kk => $vv) {
                               $store_class_names[] = $vv;
                           }
                       }
                    }
                    foreach ($_ids as $key => $value) {
                        foreach ($value as $k => $v) {
                            foreach ($v as $kk => $vv) {
                                $store_class_ids[] = $vv;
                            }
                        }
                    }
                }

            }else{
                $class_ids =array_unique($data['store_class_ids']);
                $class_names = array_unique($data['store_class_names']);
                if(!empty($class_ids)){
                    foreach ($class_ids as $value) {
                        $store_class_ids[] = trim($value,',');
                    }
                }
                if(!empty($class_names)) {
                    foreach ($class_names as $value) {
                        $store_class_names[] = trim($value,',');
                    }
                }
                if(empty($_POST['store_class_ids'])){
                    $this->error('请选择经营类目');
                } 
            }
            
            $param = array();
            $param['seller_name'] = I('seller_name');
            $param['store_name'] = I('store_name');
            $param['grade_id'] = I('grade_id');
            $param['store_class_ids'] = serialize($store_class_ids);
            $param['store_class_names'] = serialize($store_class_names);

            // TODO: 添加缴费流程
            $param['status'] = 1;
            
            $count = check_seller_name($param['seller_name']);
            if ( $count == 1) {
                $this->error('此商家账号已被注册，请重新填写');
            }
            $rules = $this->step3_rules();
            $model = D("StoreApply"); // 实例化模块
            if (!$model->validate($rules)->create()){
                // 如果创建失败 表示验证没有通过 输出错误提示信息
                $this->error($model->getError());
            }else{
                // 验证通过 可以进行其他数据操作
                $rst = false;
                $map['member_id'] = UID;
                $rst = $model->where($map)->save($param);
                $rst !== false ? $this->success('添加成功！',U('step4')) : $this->error('操作失败！');
                exit;
            }
        }
        /*读取店铺等级*/
        $grade = M('StoreGrade')->order('`sort` DESC')->select();
        $this->assign('grade',$grade);
        $this->meta_title = '店铺信息';
        $this->display();
    }
    
    
    /**
     * 入驻店铺信息验证规则
     * @return multitype:multitype:string
     */
    private function step3_rules(){
        $rules = array(
                array('seller_name','1,20','商家帐号不能为空且长度在1-20','1','length'),
                array('store_name','1,20','店铺名称不能为空且必须小于20个字！','1','length'),
                array('grade_id','require','请选择店铺等级！')
        );
        return $rules;
    }
    
    
    /**
     * 商家入驻-等待审核、审核结果
     */
    public function step4(){
        // TODO:添加数据-并跳转：入驻申请已经提交，请等待管理员审核
    	$model = M("StoreApply");
    	$map['member_id'] = UID;
    	$data = $model->where($map)->find();
    	$this->meta_title = '店铺审核';
    	$this->assign('data',$data);
        $this->display();
    }

    /**
     * AJAX获取全部分类
     * @author buddha <[email address]>
     * @return [type] [description]
     */
    public function getAllCates(){
        $pid = (I('post.pid')>0) ? I('post.pid') : 0;
        if ($pid > 0) {
            $tree[] = D('ItemCategory')->getTree($pid,'id,pid,name');
        }else{
            $tree = D('ItemCategory')->getTree(0,'id,pid,name');
        }
        $idss = $names = array();

        foreach ($tree as $key => $value) {
            if ($value['_']) {
                foreach ($value['_'] as $ke => $val) {
                    if ($val['_']) {
                        foreach ($val['_'] as $k => $v) {
                            $_ids[$ke][$k][] = $value['id'].','.$val['id'].','.$v['id'];
                            $_name[$ke][$k][] = $value['name'].','.$val['name'].','.$v['name'];
                        }
                    }else{
                        $_idss[$ke][] = $value['id'].','.$val['id'];
                        $_names[$ke][] = $value['name'].','.$val['name'];
                    }
                }
            }else{
                $ids[$key] = $value['id'];
                $name[$key] = $value['name'];
            }
            $idss[] = $ids;
            $names[] = $name;
        }
        //dump($names);
        $temp = $tep = $data = array();
        foreach ($names as $key => $value) {
            $temp = array_merge($temp,$value);
        }
        foreach ($idss as $key => $value) {
            $tep = array_merge($tep,$value);
        }
        $data['names'] = array_unique($temp);
        $data['ids'] = array_unique($tep);

        foreach ($_names as $key => $value) {
            foreach ($value as $k => $v) {
                $data['names'][] = $v;
            }
        }
        foreach ($_idss as $key => $value) {
            foreach ($value as $k => $v) {
                $data['ids'][] = $v;
            }
        }

        foreach ($_name as $key => $value) {
           foreach ($value as $k => $v) {
              foreach ($v as $kk => $vv) {
                  $data['names'][] = $vv;
              }
           }
        }
        foreach ($_ids as $key => $value) {
            foreach ($value as $k => $v) {
                foreach ($v as $kk => $vv) {
                     $data['ids'][] = $vv;
                }
            }
        }        
        //数据处理
        $str = "";
        foreach ($data['names'] as $key => $value) {
            $arr = explode(',',$value);
            $str .= "<tr><td>".$arr[0]."</td><td>".$arr[1]."</td><td>".$arr[2]."</td><td class='delet J_del_class'>删除</td>";
            $str .= "<input name='store_class_ids[]' type='hidden' value=".$data['ids'][$key].">";
            $str .= "<input name='store_class_names[]' type='hidden' value=".$value."></tr>";
        }
        $data['str'] = $str;
        echo json_encode($data);exit;
    }
    
    
}
